<template>
    <el-input v-model="claimIpt" class="w-50 m-2" size="small" placeholder="请输入姓名" :prefix-icon="Search" />
    <el-button @click="searchUser" :icon="Search" circle />
    <el-button @click="ziti"  >自提</el-button>
    <el-button @click="waimai"  >外卖</el-button>


    <el-table :data="searchTable ? searchTable : tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
        border style="width: 100%">
        <el-table-column prop="name" label="商品名称" fixed width="180">
            <template #default="scoped">
                <div
                    :style="scoped.row.schedule == '已取件' ? 'background-color:#f8e3c5' : scoped.row.schedule == '已完成' ? 'background-color:#fcd3d3' : 'background-color:white'">
                    {{ scoped.row.name }} (取货码:{{ scoped.row.phone }})
                    <p>{{ scoped.row.schedule }}</p>
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="price" label="商品价格" width="100" />
        <el-table-column prop="num" label="数量" width="100">
            <template #default="scoped">
                {{ scoped.row.num }}杯
            </template>
        </el-table-column>
        <el-table-column prop="burdening" label="选单" width="180">
            <template #default="scoped">
                {{ scoped.row.burdening.slice(1,scoped.row.burdening.length-1) }}
            </template>
        </el-table-column>
        <el-table-column prop="address" label="客人信息" width="280">
            <template #default="scoped">
                <div>
                    <div>姓名：{{ scoped.row.username }}</div>
                    <div>自提时间：{{ scoped.row.multiIndex }}</div>
                    <div>号码：{{ scoped.row.phone }}</div>

                </div>
            </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="180" />
        <el-table-column prop="pricAndtake" label="取货方式" width="100" />
        <el-table-column prop="timer" label="下单时间" width="180" />
        <el-table-column fixed="right" label="操作" width="130">
            <template #default="scoped">
                <el-button link type="primary" size="small" @click="handleClick(scoped)">已做好</el-button>
                <el-button link type="primary" size="small" @click="handleClaim(scoped)">已取件</el-button>
                <el-button link type="danger" @click="remove(scoped.row)" size="small">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination class="flex justify-center items-center mt-10" background layout="prev, pager, next"
        v-model:page-size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :total="tableData.length" />
</template>

<script setup>
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { reactive, ref, toRaw, watch } from "vue";
import { getPayList, update, removePay } from "../API/index"
import { Search } from '@element-plus/icons-vue'
//先引入下载好的插件
import Speech from 'speak-tts';
const ws = new WebSocket('ws://https://node-text-111992-4-1308764981.sh.run.tcloudbase.com');
const tableData = reactive([])

ws.onmessage = function (event) {
    const message = JSON.parse(event.data);
    voice(`来了一个新的订单，${message.data.name}${message.data.pricAndtake}`)
    setTimeout(() => {
        window.location.reload()
    }, 1000);
    // console.log(message);
    // tableData.length=0

    // getPayLists()
};
let searchTable = ref(false)
const claimIpt = ref('')
let makeOk = reactive([])
const getPayLists = async () => {
    tableData.length = 0
    let { data } = await getPayList()
    // 给商品完成情况进行标记
    data.map((item, index) => {
        if (item.schedule == '已完成') { makeOk.push(index) }

        // 将日期时间字符串转换为Date对象
        const date = new Date(item.timer);

        // 获取时间戳
        const timestamp = date.getTime();

        // 将时间戳转换为三位数
        const code = (timestamp % 1000) + 100; // 确保是三位数

        tableData.push({ ...item, claim:code,  schedule: item.schedule })
    })
    // tableData.reverse()

}
getPayLists()

// 搜索取件码
const searchUser = () => {
    let tables = toRaw(tableData)
    let index = tableData.findIndex((item) => item.username === claimIpt._value)
    if (index !== -1) {
        searchTable.value = tables.filter((item) => item.username === claimIpt._value)
        ElMessage({
            type: 'success',
            message: '查找成功'
        })
    } else {
        searchTable.value = false
        ElMessage({
            type: 'info',
            message: '未找到此商品'
        })
    }


}
// 自提
const ziti = ()=>{
    let tables = toRaw(tableData)

    searchTable.value = tables.filter((item) => item.pricAndtake === '自提')
}
// 外卖
const waimai = ()=>{
    let tables = toRaw(tableData)

    searchTable.value = tables.filter((item) => item.pricAndtake === '外卖')
}
const remove = (item) => {
    ElMessageBox.confirm(
        `确定删除${item.name}吗？`,
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let data = await removePay({ id: item.id })
            ElMessage({
                type: 'success',
                message: `删除${item.name}成功`,
            })
            getPayLists()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消',
            })
        })
}
// 制作完成
const handleClick = (item) => {
    let data = update({ id: item.row.id, schedule: '已完成' })
    voice(`取件码${item.row.id}制作完成`)
    ElMessage({
        type: 'success',
        message: '修改状态成功'
    })
    getPayLists()
}
// 制作完成
const handleClaim = (item) => {
    let data = update({ id: item.row.id, schedule: '已取件' })
    voice(`取件码${item.row.id}取件完成`)
    ElMessage({
        type: 'success',
        message: '修改状态成功'
    })
    getPayLists()

}

// watch(tableData,(newvalue,oldvalue)=>{
//     setInterval(async() => {
//         let {data} =  await getPayList()
//         if(data.length!==tableData.length){
//             // 判断原数据和最新数据的区别并筛选出来
//             let newTableList = data.splice(tableData.length,data.length)
//             newTableList.map((item)=>{
//                 voice(`新来一笔订单,${item.name}${item.pricAndtake},备注${item.remark}`)
//             })
//             getPayLists()
//         }
//     }, 3000);
// })


// 实现分页
const pageSize = ref(5)
const currentPage = ref(1)
// 分页
const handleSizeChange = (val) => {
    // 当前总数/当前页
    currentPage.value = 1
    pageSize.value = val
}
const handleCurrentChange = (val) => {
    currentPage.value = val
}


//定义一个源
const speech = new Speech();
//判断用户当前浏览器是否支持语音播报
if (speech.hasBrowserSupport()) {
    ElNotification({
        title: '语音提示',
        message: '支持语音合成',
        type: 'success',
        showClose: false,
    });
} else {
    ElNotification({
        title: '语音提示',
        message: '不支持语音合成',
        type: 'error',
        showClose: false,
    });
}
//初始化语音插件 - init内可以全部为空 - 自定义
speech
    .init({
        volume: 1, // 音量
        lang: 'zh-CN', // 语言
        rate: 1, // 语速
        pitch: 1, // 音调
        splitSentences: true, // 在句子结束时暂停
        listeners: {
            // 事件
            onvoiceschanged: voices => {
                // console.log('事件声音已更改', voices);
            },
        },
    })
    .then(data => {
        console.log('语音已准备好，声音可用', data);
    })
    .catch(e => {
        console.error('初始化时发生错误 : ', e);
    });
//语音播报按钮
function voice(title) {
    speech
        .speak({
            text: title, //这里使用文字或者i18n 都可以 看自己需求
        })
        .then(() => {
            console.log('Success !');
        })
        .catch(e => {
            console.error('An error occurred :', e);
        });
}



</script>

<style>
.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>